--
-- Author: shunguo.chen
-- Date: 2016-06-28 12:31:51
--
-- IMMessage

local fileName = string.getModeName(...)
local ClassRef = class(fileName)
local IM_CONF = nil
local message_idx = 0

function ClassRef:ctor()
	if not IM_CONF then
		IM_CONF = app:loadResScript("scripts.config.IMConfig")
	end

	-- 是系统消息（部分会出现在工会中）
	self._isFromSystem = false

	self._senderInfo = nil
	self._targetInfo = nil

	self._parseAry = nil
	self._isShareType = false

	self._textXml = nil

	self._channelStr = nil
	self._playerStr = nil
	self._audioStr = nil
	self._contentStr = nil

	self._isPlayed = false

	self._ignoreTag = false

	-- 组队招募频道的队伍id，和发布信息
	self._teamId = nil
	self._teamWords = nil
    self._teamTargetId = nil

	-- voice fileId
	self.fileId = nil

	self.channelId = ""

	self.messageId = 0
	self.text = ""
	self.from = 0
	self.timeStamp = 0
	self.messageType = 0

	self.audioPath = ""
	self.audioDuration = 0
	
	self.sessionType = 0

	self.isOutgoingMsg = false
	self.isCache = false

	self.downloadState = 0
end

-- data = S2C_InterChat
-- room = 聊天室信息
function ClassRef:init(data, room)
	message_idx = message_idx + 1
	self.messageId = message_idx
	self.messageType = im.MessageType.Text

	if data.params and data.params ~= "" then
		local replaceAry = string.split(data.params, "##")
		local index = 0
		self.text = string.gsub(data.msg, "({%d})", 
			function(v)
				index = index + 1
				if index <= #replaceAry then
					return replaceAry[index]
				end
				return v
			end)
	else
		self.text = data.msg or ""
	end

	self.timeStamp = data.timeStamp

	self:initSenderInfo(data.fromUser)
	self._senderInfo.sessionType = im.SessionType.P2p

	self.from = self._senderInfo.uid
	self.senderName = self._senderInfo.name
	
	self.isCache = data.CachedMsg
	self.isOutgoingMsg = UD:isMe(self._senderInfo.uid)
	self.downloadState = im.MessageAttachState.Downloaded

	self.sessionType = room.sessionType
	self.target = room.roomId

	self:setChannelInfo(room)
end

-- data = S2C_InterChat 
function ClassRef:initWithGM(data, room)
	self._isFromSystem = true
	self.messageId = 0
	self.messageType = im.MessageType.Text

	self.text = data.msg
	self.from = data.fromUser.uid
	self.senderName = data.fromUser.name or ""

	self.isOutgoingMsg = false
	self.downloadState = im.MessageAttachState.Downloaded

	self.target = room.roomId
	self.sessionType = im.SessionType.Chatroom

	self._senderInfo = {name=self.fromName}

	self:setChannelInfo(room)
end

function ClassRef:initWithSystem(text, room, ignoreTag)
	-- print("ignoreTag", ignoreTag)
	message_idx = message_idx + 1
	self._isFromSystem = true
	self.messageId = message_idx
	self.messageType = im.MessageType.Text

	self.text = text or ""
	self.timeStamp = math.floor(app:getServerTime())
	self.from = ""
	self.senderName = ""

	self.isOutgoingMsg = false
	self.downloadState = im.MessageAttachState.Downloaded

	self.target = room.roomId
	self.sessionType = room.sessionType

	self._senderInfo = {name="", uid=UD.player.uid}
	
	self._ignoreTag = ignoreTag

	self:setChannelInfo(room)
end

function ClassRef:initSenderInfo(user)
	local info = {}
	info.uid = user.uid
	info.name = user.name
	info.level = user.level
	info.classID = user.classID
	info.raceID = user.raceID
	info.gender = user.gender
	info.hairID = user.hairID
	info.faceID = user.faceID
	info.hairColorID = user.hairColorID
	info.mountID = user.mountID
	self._senderInfo = info
end

function ClassRef:setChannelInfo(room)
	self.channelId = room.roomId
	self.channelName = room.name
	self.channelSName = room.sname
	self:initText(self.text)
end


function ClassRef:initText(text)
	self.text = text
	if self.channelId == "system" then
		self._isShareType = false
		-- not parse system
		-- text = string.gsub(text, "<.->", "")
		-- self.text = string.xmlSpecialChars(text)

		-- parse system
		self._parseAry = self:parseText(self.text)
		-- dump(self._parseAry, "parseText")
	else
		self._parseAry = self:parseText(self.text)
		-- dump(self._parseAry, "parseText")

		-- 分享成就消息
		self._isShareType = self._parseAry[1] and self._parseAry[1].type == "s"

		-- 语音消息
		if self._parseAry[1] and self._parseAry[1].type == "v" then
			self.fileId = self._parseAry[1].id
			self.messageType = im.MessageType.Audio
			self.audioDuration = tonumber(self._parseAry[1].quality)
			self.downloadState = im.MessageAttachState.NeedDownload
			table.remove(self._parseAry, 1)
		end

		-- 组队招募 初始化self._teamId
		if self.channelId == "teamreq" then
			for i,v in ipairs(self._parseAry) do
				if v.type == "t" then
					self._teamId = v.id
                    self._teamTargetId = tonumber(v.quality)
				elseif v.type == "n" then
					self._teamWords = v.text
				end
			end
		end
	end

	-- print("IMMessage.initText", self.text)
end

function ClassRef:isCanPlay()
	return self.audioPath and #self.audioPath > 0
end

function ClassRef:needFetchAttach()
	return self.messageType == im.MessageType.Audio and
		self.downloadState == im.MessageAttachState.NeedDownload
end

function ClassRef:isTextMsg()
	return self.messageType == im.MessageType.Text
end

function ClassRef:isAudioMsg()
	return self.messageType == im.MessageType.Audio
end

function ClassRef:setAudioPath(path)
	self.audioPath = path
end

function ClassRef:setDownloadState(state)
	self.downloadState = state
	-- if state == im.MessageAttachState.Downloaded then
	-- 	self._textXml = nil
	-- 	self._audioStr = nil
	-- end
end

function ClassRef:isPlayed()
	return self._isPlayed
end
function ClassRef:setIsPlayed(b)
	self._isPlayed = b
end

function ClassRef:setAudioText(text)
	self:initText(text or "")
	self._textXml = nil
end

function ClassRef:setTargetInfo(info)
	self._targetInfo = info
end
function ClassRef:getTargetInfo()
	return self._targetInfo
end

function ClassRef:getSenderInfo()
	return self._senderInfo
end

-- p2p 聊天对象info
function ClassRef:getP2pInfo()
	return self.isOutgoingMsg and self._targetInfo or self._senderInfo
end

function ClassRef:getSenderName()
	return self._senderInfo.name
end

function ClassRef:getUid()
	return self._senderInfo.uid
end

function ClassRef:getTarget()
	if self.sessionType == im.SessionType.P2p then 
		return self.isOutgoingMsg and self._targetInfo.uid or self.from
	else
		return self.target
	end
end

function ClassRef:isFromSystem()
	return self._isFromSystem
end

function ClassRef:isTeamMsg()
    return self.channelId == "team"
end

function ClassRef:isTeamreqMsg()
	return self.channelId == "teamreq"
end
function ClassRef:isP2pMsg()
	return self.channelId == "p2p"
end

function ClassRef:getTeamId()
	if self.channelId ~= "teamreq" then return end
	return self._teamId
end

function ClassRef:getTeamTargetId()
    if self.channelId ~= "teamreq" then return end
    return self._teamTargetId
end

function ClassRef:getTeamWords()
	if self.channelId ~= "teamreq" then return end
	return self._teamWords
end

function ClassRef:getChannelColor()
	return display.color3BWithString(self:getChannelColorStr())
end

function ClassRef:getChannelColorStr()
	if self.sessionType == im.SessionType.Chatroom then
		return IM_CONF.channelColor[self.channelId] or IM_CONF.channelColor["def"]
	elseif self.sessionType == im.SessionType.P2p then
		return IM_CONF.channelColor.p2p
	elseif self.sessionType == im.SessionType.Team then
		return IM_CONF.channelColor.team
	end
end

function ClassRef:getFontColor()
	if self.sessionType == im.SessionType.Chatroom then
		return IM_CONF.fontColor[self.channelId] or IM_CONF.fontColor["def"]
	elseif self.sessionType == im.SessionType.P2p then
		return IM_CONF.fontColor.p2p
	elseif self.sessionType == im.SessionType.Team then
		return IM_CONF.fontColor.team
	end
end

function ClassRef:getChannelStr()
	if self._ignoreTag then return "" end
	if self._channelStr == nil then
		self._channelStr = display.getRichTextFontXml("[" .. self.channelName .. "]", self:getChannelColorStr())
	end
	return self._channelStr
end

function ClassRef:getPlayerStr(size)
	if self._isShareType then return "" end
	if self._playerStr == nil then
		local ret
		if self.sessionType == im.SessionType.P2p then
			if self.isOutgoingMsg then
				ret = display.getRichTextUrlXml(self._targetInfo.name, "p|target", true, IM_CONF.playerColor)
				ret = display.getRichTextFontXml("[" .. ret .. "]", IM_CONF.playerColor)
				ret = string.format(L("text_11400013"), ret) .. ": "
			else
				ret = display.getRichTextUrlXml(self._senderInfo.name, "p|sender", true, IM_CONF.playerColor)
				ret = display.getRichTextFontXml("[" .. ret .. "]", IM_CONF.playerColor)
				ret = string.format(L("text_11400014"), ret) .. ": "
			end
		else
			if self.isOutgoingMsg then
				ret = display.getRichTextFontXml(L("text_11400016"), IM_CONF.myColor)
				ret = ret .. ": "
			else
				-- print("self.channelId = " .. self.channelId)
				-- if self.channelId == "system" then 
				if self._senderInfo.name == "" then 
					-- 名字为空，不需要 "[]: "
					-- ret = display.getRichTextFontXml("", IM_CONF.playerColor)
					ret = ""
				else
					ret = display.getRichTextUrlXml(self._senderInfo.name, "p|sender", true, IM_CONF.playerColor)
					ret = display.getRichTextFontXml("[" .. ret .. "]", IM_CONF.playerColor)
					ret = ret .. ": "
				end
			end
		end
		self._playerStr = ret
	end
	if size then
		return display.getRichTextFontXml(self._playerStr, nil, size)
	else
		return self._playerStr
	end
end

function ClassRef:getAudioStr()
	if self.messageType == im.MessageType.Audio then
		if self._audioStr == nil or string.len(self._audioStr) == 0 then
			local str = string.format("[" .. L("tips_3000179") .. "]", self.audioDuration)
			if self:isTeamreqMsg() then -- 组队招募语音不显示语音长度
				str = string.format("[" .. L("teamReqAudioTips") .. "]")
			end
			self._audioStr = display.getRichTextFontXml(str, self:getFontColor())
		end
	else
		self._audioStr = ""
	end
	return self._audioStr
end

function ClassRef:getContentStr()
	if self._contentStr == nil or string.len(self._contentStr) == 0 then
		-- if self.channelId == "system" then
		-- 	self._contentStr = display.getRichTextFontXml(self.text, self:getFontColor())
		-- else
			local strAry = {}
			for i, v in ipairs(self._parseAry) do
				local text = v.text--string.xmlSpecialChars(v.text)
				if v.type == "f" then
					strAry[#strAry + 1] = display.getRichTextImgXml(text, 24, 24)
				elseif v.type == "e" then
					local colorStr = display.stringWithColor(Enums.QualityColor[tonumber(v.quality)])
					local cont = string.sub(text, 2, -2)
					local puid = v.puid or self._senderInfo.uid
					local param = "e|" .. v.id .. "|".. puid
					if v.uid then
						param = param .. "|" .. v.uid
					end
					cont = display.getRichTextUrlXml(cont, param, true, colorStr)
					strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
				elseif v.type == "m" or v.type == "h" or v.type == "z"then
					local colorStr = display.stringWithColor(Enums.QualityColor[tonumber(v.quality)])
					local cont = string.sub(text, 2, -2)
					local url = table.concat({v.type, v.id, v.quality, v.uid}, "|")
					cont = display.getRichTextUrlXml(cont, url, true, colorStr)
					strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
				elseif v.type == "r" then
					local colorStr = display.stringWithColor(Enums.QualityColor[tonumber(v.quality)])
					local cont = string.sub(text, 2, -2)
					cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, colorStr)
					strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
				elseif v.type == "q" then
					local colorStr = display.stringWithColor(Enums.QualityColor[2])
					local cont = string.sub(text, 2, -2)
					cont = display.getRichTextUrlXml(cont, "q|" .. v.id, true, colorStr)                     
					strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)   
				elseif v.type == "t" then
					local cont = string.sub(text, 2, -2)
					local url = display.getRichTextUrlXml(L("text_11400015"), v.type .. "|" .. v.id, true, IM_CONF.joinTeamColor)                     
					strAry[#strAry + 1] = cont.."<br />"..display.getRichTextFontXml("[" .. url .. "]", IM_CONF.joinTeamColor)
				elseif v.type == "g" then
					local cont = string.sub(text, 2, -2)
					cont = string.trim(cont)
					if string.find(cont, "[\t\n\r]") then
						cont = string.gsub(cont, "[\t\n\r]", "") -- 去掉换行
					end
					cont = string.format(L("guild_des_recruit"), v.quality, cont) -- 公会宣言需要进一步处理
					local url = display.getRichTextUrlXml(L("text_11400015"), v.type .. "|" .. v.id, true, IM_CONF.joinTeamColor)                     
					strAry[#strAry + 1] = cont.."<br />"..display.getRichTextFontXml("[" .. url .. "]", IM_CONF.joinTeamColor)
				elseif v.type == "a" then
					local cont = string.sub(text, 2, -2)
					cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id.."|"..v.quality, true, IM_CONF.achieveColor)                   
					strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", IM_CONF.achieveColor)
				elseif v.type == "u" then
					local cont = string.sub(text, 2, -2)
					cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, IM_CONF.joinTeamColor)                   
					strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", IM_CONF.joinTeamColor)
				elseif v.type == "i" or v.type == "c" or v.type == "j" then
					local colorStr = display.stringWithColor(Enums.QualityColor[tonumber(v.quality)])
					local cont = string.sub(text, 2, -2)
					cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, colorStr)                     
					strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
				elseif v.type == "o" then
					local cont = string.sub(text, 2, -2)
					cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, IM_CONF.captainRoomColor)
					strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", IM_CONF.captainRoomColor)
				elseif v.type == "d" then
					local cont = string.sub(text, 2, -2)
					cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, IM_CONF.captainRoomColor)
					strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", IM_CONF.captainRoomColor)
				elseif v.type == "s" then
					strAry[#strAry + 1] = string.sub(text, 2, -2)            
				else
					strAry[#strAry + 1] = text
				end
			end
			self._contentStr = display.getRichTextFontXml(table.concat(strAry), self:getFontColor())
			-- print("IMMessage.contentStr = " .. self._contentStr)
		-- end
	end
	return self._contentStr
end

function ClassRef:getRoomTextXml()
	local ary = {"", self:getContentStr()}
	if self:isAudioMsg() then
		ary[1] = display.getRichTextCSBXml(Res.IMVoiceBtn, 100, 144, 35) .. "<br />"
	end
	return table.concat(ary)
end

function ClassRef:getSimpleTextXml()
	if self._textXml == nil then 
		local contStr = self:getContentStr()
		contStr = string.gsub(contStr, "='24' ", "='22' ")
        if self:isTeamreqMsg() then
            contStr = string.gsub(contStr, "<br />", "")
        end
		-- print("contStr", contStr)
		local strAry = {self:getChannelStr(), self:getPlayerStr(), self:getAudioStr(), contStr}
		self._textXml = table.concat(strAry)
	end
	return self._textXml
end

function ClassRef:getPpColorStr()
	return "#000000"
	-- if self.sessionType == im.SessionType.Chatroom then
	-- 	return IM_CONF.ppColor[self.channelId] or IM_CONF.ppColor["def"]
	-- elseif self.sessionType == im.SessionType.P2p then
	-- 	return IM_CONF.ppColor.p2p
	-- elseif self.sessionType == im.SessionType.Team then
	-- 	return IM_CONF.ppColor.team
	-- end
end

function ClassRef:getPpChannelStr()
	if self._ignoreTag then 
		return "" 
	else
		return display.getRichTextFontXml("[" .. self.channelName .. "]", self:getPpColorStr())
	end
end

function ClassRef:getPpPlayerStr()
	if self._isShareType then return "" end
	local ret
	if self.sessionType == im.SessionType.P2p then
		if self.isOutgoingMsg then
			ret = display.getRichTextUrlXml(self._targetInfo.name, "p|target", true, IM_CONF.ppOtherColor)
			ret = display.getRichTextFontXml("[" .. ret .. "]", IM_CONF.ppOtherColor)
			ret = string.format(L("text_11400013"), ret) .. ": "
		else
			ret = display.getRichTextUrlXml(self._senderInfo.name, "p|sender", true, IM_CONF.ppOtherColor)
			ret = display.getRichTextFontXml("[" .. ret .. "]", IM_CONF.ppOtherColor)
			ret = string.format(L("text_11400014"), ret) .. ": "
		end
	else
		if self.isOutgoingMsg then
			ret = display.getRichTextFontXml(L("text_11400016"), IM_CONF.ppMyColor)
			ret = ret .. ": "
		else
			-- print("self.channelId = " .. self.channelId)
			if self.channelId == "system" then 
				--系统消息 不能点击
				ret = display.getRichTextFontXml("", IM_CONF.ppOtherColor)
			else
				ret = display.getRichTextUrlXml(self._senderInfo.name, "p|sender", true, IM_CONF.ppOtherColor)
				ret = display.getRichTextFontXml("[" .. ret .. "]", IM_CONF.ppOtherColor)
				ret = ret .. ": "
			end
		end
	end
	return ret
end

function ClassRef:getPpAudioStr()
	if self.messageType == im.MessageType.Audio then
		if self._audioStr == nil or string.len(self._audioStr) == 0 then
			local str = string.format("[" .. L("tips_3000179") .. "]", self.audioDuration)
			if self:isTeamreqMsg() then -- 组队招募语音不显示语音长度
				str = string.format("[" .. L("teamReqAudioTips") .. "]")
			end
			return display.getRichTextFontXml(str, self:getPpColorStr())
		end
	end
	return ""
end

-- pp 文本不同颜色展示
-- function ClassRef:getPpContentStr()
--	if self.channelId == "system" then
--		return display.getRichTextFontXml(self.text, self:getPpColorStr())
--	end

-- 	local strAry = {}
-- 	for i, v in ipairs(self._parseAry) do
-- 		local text = string.xmlSpecialChars(v.text)
-- 		if v.type == "f" then
-- 			strAry[#strAry + 1] = display.getRichTextImgXml(text, 24, 24)
-- 		elseif v.type == "e" then
-- 			local colorStr = display.stringWithColor(Enums.QualityColor[tonumber(v.quality)])
-- 			local cont = string.sub(text, 2, -2)
--			local puid = v.puid or self._senderInfo.uid
--			local param = "e|" .. v.id .. "|".. puid
--			if v.uid then
--				param = param .. "|" .. v.uid
--			end
-- 			cont = display.getRichTextUrlXml(cont, param, true, colorStr)
-- 			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
-- 		elseif v.type == "m" then
-- 			local colorStr = display.stringWithColor(Enums.QualityColor[tonumber(v.quality)])
-- 			local cont = string.sub(text, 2, -2)
--			local url = table.concat({v.type, v.id, v.quality, v.uid}, "|")
-- 			cont = display.getRichTextUrlXml(cont, url, true, colorStr)
-- 			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
-- 		elseif v.type == "r" then
-- 			local colorStr = display.stringWithColor(Enums.QualityColor[tonumber(v.quality)])
-- 			local cont = string.sub(text, 2, -2)
-- 			cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, colorStr)
-- 			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
-- 		elseif v.type == "q" then
-- 			local colorStr = display.stringWithColor(Enums.QualityColor[2])
-- 			local cont = string.sub(text, 2, -2)
-- 			cont = display.getRichTextUrlXml(cont, "q|" .. v.id, true, colorStr)                     
-- 			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)   
-- 		elseif v.type == "t" or v.type == "a" then
-- 			local cont = string.sub(text, 2, -2)
-- 			cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, IM_CONF.joinTeamColor)                     
-- 			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", IM_CONF.joinTeamColor)
-- 		elseif v.type == "i" or v.type == "c" or v.type == "j" then
-- 			local colorStr = display.stringWithColor(Enums.QualityColor[tonumber(v.quality)])
-- 			local cont = string.sub(text, 2, -2)
-- 			cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, colorStr)                     
-- 			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
-- 		elseif v.type == "s" then
-- 			strAry[#strAry + 1] = string.sub(text, 2, -2)
-- 		else
-- 			strAry[#strAry + 1] = text
-- 		end
-- 	end
-- 	return display.getRichTextFontXml(table.concat(strAry), self:getPpColorStr())
-- end

-- pp 文本同一颜色展示
function ClassRef:getPpContentStr()
	-- if self.channelId == "system" then
	-- 	return display.getRichTextFontXml(self.text, self:getPpColorStr())
	-- end

	local strAry = {}
	local colorStr = "#000000"
	for i, v in ipairs(self._parseAry) do
		local text = v.text --string.xmlSpecialChars(v.text)
		if v.type == "f" then
			strAry[#strAry + 1] = display.getRichTextImgXml(text, 24, 24)
		elseif v.type == "e" then
			local cont = string.sub(text, 2, -2)
			local puid = v.puid or self._senderInfo.uid
			local param = "e|" .. v.id .. "|".. puid
			if v.uid then
				param = param .. "|" .. v.uid
			end
			cont = display.getRichTextUrlXml(cont, param, true, colorStr)
			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
		elseif v.type == "m" or v.type == "h" or v.type == "z" then
			local cont = string.sub(text, 2, -2)
			local url = table.concat({v.type, v.id, v.quality, v.uid}, "|")
			cont = display.getRichTextUrlXml(cont, url, true, colorStr)
			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
		elseif v.type == "r" then
			local cont = string.sub(text, 2, -2)
			cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, colorStr)
			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
		elseif v.type == "q" then
			local cont = string.sub(text, 2, -2)
			cont = display.getRichTextUrlXml(cont, "q|" .. v.id, true, colorStr)                     
			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
		elseif v.type == "t" then
			local cont = string.sub(text, 2, -2)
			local url = display.getRichTextUrlXml(L("text_11400015"), v.type .. "|" .. v.id, true, colorStr)                     
			strAry[#strAry + 1] = cont.."<br />"..display.getRichTextFontXml("[" .. url .. "]", colorStr)
		elseif v.type == "g" then
			local cont = string.sub(text, 2, -2)
			cont = string.trim(cont)
			if string.find(cont, "[\t\n\r]") then
				cont = string.gsub(cont, "[\t\n\r]", "") -- 去掉换行
			end
			cont = string.format(L("guild_des_recruit"), v.quality, cont) -- 公会宣言需要进一步处理
			local url = display.getRichTextUrlXml(L("text_11400015"), v.type .. "|" .. v.id, true, colorStr)                     
			strAry[#strAry + 1] = cont.."<br />"..display.getRichTextFontXml("[" .. url .. "]", colorStr)               
		elseif v.type == "a" or v.type == "u" or v.type == "d" then
			local cont = string.sub(text, 2, -2)
			cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, colorStr)                     
			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
		elseif v.type == "i" or v.type == "c" or v.type == "j" then
			local cont = string.sub(text, 2, -2)
			cont = display.getRichTextUrlXml(cont, v.type .. "|" .. v.id, true, colorStr)                     
			strAry[#strAry + 1] = display.getRichTextFontXml("[" .. cont .. "]", colorStr)
		elseif v.type == "s" then
			strAry[#strAry + 1] = string.sub(text, 2, -2)
		else
			strAry[#strAry + 1] = text
		end
	end
	return display.getRichTextFontXml(table.concat(strAry), self:getPpColorStr())
end

function ClassRef:getPpTextXml()
	-- local strAry = {self:getPpChannelStr(), self:getPpPlayerStr(), self:getPpAudioStr(), self:getPpContentStr()}
	local strAry = {self:getPpAudioStr(), self:getPpContentStr()}
	return table.concat(strAry)
end

-- str=#s01something[e|长矛|10002]youle
-- ret = {{text=s01, type="f"},{text=somethine, type="n"},...}
-- type="f|" 表情
-- type="e|" 武器装备
-- type="m|" 坐骑
-- type="q|" 任务
-- type="t|" 组队
-- type="i|" 道具
-- type="c|" 合成配方
-- type="a|" 成就achieve
-- type="r|" 符文rune
-- type="j|" 珠宝jewel
-- type="h|" 随从partner
-- type="z|" 时装clothes
-- type="s|" 分享share
-- type="u|" 玩家名字 内容中提到的需要link的玩家
-- type="v|" 声音voice，v|录音|fileId|duration
-- type="o|" 船长室
-- type="g|" 公会宣言guild
-- type="d|" 决斗 d|stringId,name1,name2|uid
-- type="n"/其他 普通文本
-- 
-- type="p|" 玩家名字 消息发送者／接收者（不会被解析）
-- type="audio|" 音频（不会被解析）
function ClassRef:parseText(str)
	local ret = {}

	local function checkFace(sourceStr)
		local splitStr = "(#%d+)"
		local startIdx = 1
		local strLen = string.len(sourceStr)
		while strLen > 0 do
			local sIdx, eIdx, catch = string.find(sourceStr, splitStr, startIdx)
			if sIdx ~= nil then
				if sIdx > startIdx then
					local text = string.sub(sourceStr, startIdx, sIdx-1)
					if #ret > 0 and ret[#ret].type == "n" then
						ret[#ret].text = ret[#ret].text .. text
					else
						ret[#ret+1] = {text=text, type="n"}
					end
				end

				local iconRes = "art/chat_icon/s".. string.sub(catch, 2, -1) ..".png" -- 表情中去掉的s在解析的时候要重新加上
				if cc.FileUtils:getInstance():isFileExist(iconRes) then
					ret[#ret+1] = {text=iconRes, type="f"}
				else
					if #ret > 0 and ret[#ret].type == "n" then
						ret[#ret].text = ret[#ret].text .. catch
					else
						ret[#ret+1] = {text=catch, type="n"}
					end
				end

				startIdx = eIdx + 1
			else
				if startIdx <= strLen then
					local text = string.sub(sourceStr, startIdx, strLen)
					ret[#ret+1] = {text=text, type="n"}
				end
				break
			end
		end
	end

	local splitStr = "(%[[emtiqjcarsuvhzogd]|[^%[%]]+%])"
	local startIdx = 1
	local strLen = string.len(str)
	while strLen > 0 do
		local sIdx, eIdx, catch = string.find(str, splitStr, startIdx)
		if sIdx ~= nil then
			if sIdx > startIdx then
				local text = string.sub(str, startIdx, sIdx-1)
				checkFace(text)
			end

			local text = string.sub(catch, 2, -2)
			local ary = string.split(text, "|")

			-- ary[2] 内容最复杂可能是 tips_1002,12,tips_1001;1;好 -》string.format(L(tips_1002), 12, L(tips_1001)) .. 1好
			local con = ary[2]
			local new_con = ""
			if string.isContain(con, ";") then
				local contAry = string.split(con, ";")
				con = contAry[1]
				for i,v in ipairs(contAry) do
					if i > 1 then
						new_con = new_con .. v
					end
				end
			end
			if string.isContain(con, ",") then
				local contAry = string.split(con, ",")
				for i,v in ipairs(contAry) do
					contAry[i] = L(v)
				end
				con = table.remove(contAry, 1)
				new_con = string.format(con, unpack(contAry)) .. new_con
			else
				new_con = L(con) .. new_con
			end

			ret[#ret+1] = {type=ary[1], text="[" .. new_con .. "]", id=ary[3], quality=ary[4], uid=ary[5], puid=ary[6]}

			startIdx = eIdx + 1
		else
			if startIdx <= strLen then
				local text = string.sub(str, startIdx, strLen)
				checkFace(text)
			end
			break
		end
	end
	return self.channelId ~= "system" and self:interceptsStrToMaxLen(ret) or ret
end

-- 字符串最大长度
function ClassRef:interceptsStrToMaxLen(ret)
	if not ret then return end
	local wordLen = 0
	local retArray = {}
	for k, v in ipairs(ret) do
		if v.type == "f" then -- 表情算一个字符
			wordLen = wordLen + 1
		elseif v.type == "n" or v.type == "g" then
			if string.ulen(v.text) > Constant.MAX_WORD_LEN - wordLen then
				v.text = string.usubstr(v.text, math.max(Constant.MAX_WORD_LEN - wordLen, 1))
			end
			wordLen = wordLen + string.ulen(v.text)
		else
			wordLen = wordLen + string.ulen(v.text)
		end
		if wordLen <= Constant.MAX_WORD_LEN then
			retArray[#retArray+1] = v
		else
			retArray[#retArray+1] = {text="...", type="n"}
			break
		end
	end
	return retArray
end

return ClassRef